package net.ck.hzq;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.List;

import Bean.AddMPOSBean;
import Bean.AddMPOSParamBean;
import Bean.PhoneNumerBean;
import Bean.PhoneNumerParamBean;
import Utils.CheckPermissionUtils;
import Utils.HelloWordModel;
import Utils.SystemDatas;
import Utils.TimeCount;
import pos.ScanActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Response;

public class ActivationregistrationActivity extends Activity implements View.OnClickListener, EasyPermissions
        .PermissionCallbacks {

    private TimeCount timeCount;

    public static final int REQUEST_CODE = 111;

    private ImageView activationregistration_back;

    private TextView txt_activationregistration_automaticrecognition;

    private EditText edit_activationregistration_phone, edit_activationregistration_serialnumber,
            edit_activationregistration_name;

    private Button activationregistration_but;


    private SharedPreferences sp;

    // 验证码
    private CountDownTimer timer;
    private String mCode;
    private TextView getVerifyCode;
    private EditText verifyCodeEt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activationregistration);

        TobuyApplication.getmInstance().onActivityCreate(this);


        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);

        initPermission();

        edit_activationregistration_phone = findViewById(R.id.edit_activationregistration_phone);
        edit_activationregistration_name = findViewById(R.id.edit_activationregistration_name);
        activationregistration_but = findViewById(R.id.activationregistration_but);
        activationregistration_back = findViewById(R.id.activationregistration_back);
        txt_activationregistration_automaticrecognition = findViewById(R.id
                .txt_activationregistration_automaticrecognition);
        activationregistration_back.setOnClickListener(new ButtonOnClickListener(activationregistration_back.getId()));
        txt_activationregistration_automaticrecognition.setOnClickListener(new ButtonOnClickListener
                (txt_activationregistration_automaticrecognition.getId()));
        edit_activationregistration_serialnumber = findViewById(R.id.edit_activationregistration_serialnumber);

        activationregistration_but.setOnClickListener(this);

        // 验证码
        getVerifyCode = findViewById(R.id.get_verify_code);
        verifyCodeEt = findViewById(R.id.et_verify_code);
        getVerifyCode.setOnClickListener(this);
    }

    class ButtonOnClickListener implements View.OnClickListener {

        private int buttonId;

        public ButtonOnClickListener(int buttonId) {
            this.buttonId = buttonId;
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.activationregistration_back) {
                finish();
            } else {
                cameraTask(buttonId);
            }
        }
    }

    private void initPermission() {
        String[] permissions = CheckPermissionUtils.checkPermission(this);
        if (permissions.length == 0) {
        } else {
            ActivityCompat.requestPermissions(this, permissions, 100);
        }
    }

    public void onClick(int id) {
        switch (id) {
            case R.id.txt_activationregistration_automaticrecognition:
                IntentIntegrator integrator = new IntentIntegrator(ActivationregistrationActivity.this);
                // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
                integrator.setCaptureActivity(ScanActivity.class); //设置打开摄像头的Activity
                integrator.setPrompt("请扫描SN"); //底部的提示文字，设为""可以置空
                integrator.setCameraId(0); //前置或者后置摄像头
                integrator.setBeepEnabled(true); //扫描成功的「哔哔」声，默认开启
                integrator.setBarcodeImageEnabled(true);
                integrator.initiateScan();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activationregistration_but:
                if (edit_activationregistration_name.getText().toString().trim() == null | edit_activationregistration_name
                        .getText().toString().trim().equals("")) {
                    Toast.makeText(ActivationregistrationActivity.this, "请输入客户姓名!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (edit_activationregistration_phone.getText().toString().trim() == null | edit_activationregistration_phone
                        .getText().toString().trim().equals("")) {
                    Toast.makeText(ActivationregistrationActivity.this, "请输入手机号!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(verifyCodeEt.getText().toString().trim())) {
                    Toast.makeText(ActivationregistrationActivity.this, "请输入验证码!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mCode) || !TextUtils.equals(mCode, verifyCodeEt.getText().toString().trim())) {
                    Toast.makeText(ActivationregistrationActivity.this, "请输入正确的验证码!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (edit_activationregistration_serialnumber.getText().toString().trim() == null |
                        edit_activationregistration_serialnumber.getText().toString().trim().equals("")) {
                    Toast.makeText(ActivationregistrationActivity.this, "请识别产品条形码!", Toast.LENGTH_SHORT).show();
                    return;
                }

                AddMPOSParamBean a = new AddMPOSParamBean();
                a.setPosCustomId(Integer.parseInt(sp.getString("id", null)));
                a.setCustomName(edit_activationregistration_name.getText().toString().trim());
                a.setCustomPhoneNumber(edit_activationregistration_phone.getText().toString().trim());
                a.setPosNnstanceSn(edit_activationregistration_serialnumber.getText().toString().trim().replace("\n", ""));
                a.setRegion("a88c3b60-9c31-4145-9a47-84b7847e28d3");
                Call<AddMPOSBean> userMsgCall5 = HelloWordModel.getInstance(this).addMPOS(SystemDatas.GetService_URL("addmpos")
                        , a);
                userMsgCall5.enqueue(new retrofit2.Callback<AddMPOSBean>() {
                    @Override
                    public void onResponse(Call<AddMPOSBean> call, final Response<AddMPOSBean> response) {

                        try {
                            if (response.body().getMsg().equals("success")) {

                                Toast.makeText(ActivationregistrationActivity.this, "提交成功!", Toast.LENGTH_SHORT).show();

                            } else {
                                Toast.makeText(ActivationregistrationActivity.this, "提交失败!", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<AddMPOSBean> call, Throwable t) {
                        Toast.makeText(ActivationregistrationActivity.this, "提交失败!", Toast.LENGTH_SHORT).show();
                    }
                });
                finish();
                break;
            case R.id.get_verify_code:
                if (edit_activationregistration_phone.getText().toString().trim() == null | edit_activationregistration_phone
                        .getText().toString().trim().equals("")) {
                    Toast.makeText(ActivationregistrationActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (timer != null) {
                    timer.cancel();
                }
                getVerifyCode.setEnabled(false);
                timer = new CountDownTimer(60000, 1000) {
                    @Override
                    public void onTick(long l) {
                        getVerifyCode.setText(l / 1000 + "秒后重发");
                    }

                    @Override
                    public void onFinish() {
                        getVerifyCode.setEnabled(true);
                        getVerifyCode.setText("获取验证码");
                    }
                };
                timer.start();

                PhoneNumerParamBean p = new PhoneNumerParamBean();
                p.setTelephoneNumber(edit_activationregistration_phone.getText().toString().trim());
                Call<PhoneNumerBean> userMsgCall2 = HelloWordModel.getInstance(this).getphonecode(SystemDatas.GetService_URL
                        ("getphonecode2"), p);
                userMsgCall2.enqueue(new retrofit2.Callback<PhoneNumerBean>() {
                    @Override
                    public void onResponse(Call<PhoneNumerBean> call, final Response<PhoneNumerBean> response) {

                        try {
                            if (response.body().getMsg().equals("success")) {
                                Toast.makeText(ActivationregistrationActivity.this, "获取成功!", Toast.LENGTH_SHORT).show();
                                mCode = response.body().getData().getCode();
                            } else {
                                Toast.makeText(ActivationregistrationActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT)
                                        .show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<PhoneNumerBean> call, Throwable t) {
                        Toast.makeText(ActivationregistrationActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
                    }
                });

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //处理扫描结果（在界面上显示）
//            if (null != data) {
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            String result = scanResult.getContents();
            edit_activationregistration_serialnumber.setText(result);
        }
//        } else if (requestCode == REQUEST_CAMERA_PERM) {
//            Toast.makeText(this, "从设置页面返回...", Toast.LENGTH_SHORT)
//                    .show();
//        }
    }

    public static final int REQUEST_CAMERA_PERM = 101;


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @AfterPermissionGranted(REQUEST_CAMERA_PERM)
    public void cameraTask(int viewId) {
        if (EasyPermissions.hasPermissions(this, android.Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            onClick(viewId);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要请求camera权限",
                    REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Toast.makeText(this, "执行onPermissionsGranted()...", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(this, "执行onPermissionsDenied()...", Toast.LENGTH_SHORT).show();
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "当前App需要申请camera权限,需要打开设置页面么?")
                    .setTitle("权限申请")
                    .setPositiveButton("确认")
                    .setNegativeButton("取消", null /* click listener */)
                    .setRequestCode(REQUEST_CAMERA_PERM)
                    .build()
                    .show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
